<template>
  <div class="bg-gray-100 dark:bg-gray-900 min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md p-8 bg-white dark:bg-gray-800 rounded shadow">
      <h2 class="text-2xl font-bold mb-6 text-center text-gray-900 dark:text-gray-100">注册</h2>
      <el-form ref="formRef" :model="form" label-position="top">
        <el-form-item label="邮箱">
          <el-input v-model="form.mail" placeholder="请输入 QQ 邮箱" clearable />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password clearable />
        </el-form-item>
        <el-form-item label="验证码">
          <div class="flex w-full">
            <el-input v-model="form.code" placeholder="请输入验证码" clearable />
            <el-button class="ml-2" :loading="sending" @click="onSendCode">发送验证码</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-full" :loading="loading" @click="onSubmit">注册</el-button>
        </el-form-item>
        <div class="text-center text-gray-600 dark:text-gray-300">
          已有账号？<a class="text-blue-500" @click="toLogin">去登录</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showMessage } from '@/composables/util'
import { sendRegisterCode, register } from '@/api/admin/user'

const router = useRouter()

const formRef = ref(null)
const form = reactive({
  mail: '',
  password: '',
  code: ''
})

const sending = ref(false)
const loading = ref(false)

const onSendCode = () => {
  if (!form.mail) {
    showMessage('请先输入邮箱', 'warning')
    return
  }
  sending.value = true
  sendRegisterCode(form.mail)
    .then(res => {
      if (res.success) {
        showMessage('验证码已发送，请查看邮箱')
      } else {
        showMessage(res.message || '发送失败', 'error')
      }
    })
    .finally(() => sending.value = false)
}

const onSubmit = () => {
  if (!form.mail || !form.password || !form.code) {
    showMessage('请完整填写信息', 'warning')
    return
  }
  loading.value = true
  register(form.mail, form.password, form.code)
    .then(res => {
      if (res.success) {
        showMessage('注册成功，请登录')
        router.push('/login')
      } else {
        showMessage(res.message || '注册失败', 'error')
      }
    })
    .finally(() => loading.value = false)
}

const toLogin = () => router.push('/login')
</script>

<style scoped>
</style> 